import DataType from './utils/data-type'
import Storage from './core/storage'
import Query from './core/query'
import Rest from './core/rest'
import Inner from './core/inner'
import Router from './core/router'
import FormTable from './core/form-table'
import FormRow from './core/form-row'

/* ====================================== 全局变量及方法  ====================================== */
const _ = {
	// ======================================================================== 功能函数
	...DataType,
	...Storage,
	...Query,
	...Rest,
	...Inner,
	...Router,
	...FormTable,
	...FormRow,
	// ======================================================================== 全局变量
	c0:'#208fa0',
	menuWidth: 150,
	// ======================================================================== 表格配置
	table:{
		time:{ width:140, align:'left' },
		date:{ width:80, align:'left' },
		name: { width:90 },
		status: { width:80 },
		age: { width:60, render: (text, { age,  age_first_val, age_first_type_name }) => {
			return age ? age : age_first_val + age_first_type_name
		}},
		sex: { width:60, align:'left' },
		idcard: { width:200, align:'left' },
		card_type: { width:150, align:'left' },
		spec_num: { width:130, align:'left' },
		exp_num: { width:100 },
		num: { width:80 },
		hosp_code:{width:130, align:'left'},
		phone: { width:120, align:'left' },
		spec_code: { width:130, render: text => {
			if(text){
				return _.getSplitSpecCode(text)
			}else{
				return '--'
			}
		} },
		controls : { width:120, align:'left', className:'controls', fixed:'right' },
		isDefault: { width:100, render: text => +text===1 ? '是' : '否' }
	},
	// ======================================================================== 菜单配置
	menu:{
		preview_report: { title: '预览报告单', 	path: 'preview-report', component:'_public/preview-report', cache:true },
		preview_audit_report: { title: '预览并批准报告单', path: 'preview-audit-report', component:'_public/preview-audit-report', cache:true },
		patient_detail:	{ title: '修改资料', 	path: 'patient-detail', component:'_public/patient-detail', cache:true },
	},
	// ======================================================================== 正则匹配
	//	isTel(v){ return /^1[0-9]{10}$/.test(v) },
		isPwd(v){ return /^.{6,18}$/.test(v) },
	//	pwdReg: /\w{6,18}$/,
	//	isId(v){ return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(v) },
	//	isCard(v){ return /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X|x)$/.test(v) },
	//	isCard(v){ return true},
		isEmail(v){ return /^([0-9A-Za-z\-_]+)@([0-9a-z]+\.[a-z]{2,3}(\.[a-z]{2})?)$/g.test(v) },
	//	isInt(v){ return /^[1-9]\d*$/.test(v) }, // 整数
	// 刷新 key
	refresh(_this){ _this.setState({ key: (_this.state.key || 0) + 1}) },
	// 储存与获取数据
	getData(_this, api, {dataName = 'data',loadingTxt='loading'}){
		const { $fn, $http } = window
		const data = $fn.local(api)
		if ($fn.hasArray(data)) {
			_this.setState({ [dataName]:data, [loadingTxt]:false })
		} else {
		    $http.submit(null, api).then(data => {
		        _this.setState({ [dataName]:data, [loadingTxt]:false })
				$fn.local(api,data)
		    })
		}
	},
	// 获取下拉框数据
	async getSelect(api){
		const { $fn, $http } = window
		const data = $fn.local(api)
		if ($fn.hasArray(data)) {
			return data
		} else {
		    return await $http.pull(null, api).then(data => {
				$fn.local(api,data)
				return data;
		    })
		}
	},
	// 将下拉框数据赋给 submit 数据
	setSubmitSelect(name, submit, data ){
		const rows = submit.filter(v => v.name === name)
		if(this.hasArray(rows)){ rows[0]['data'] = data }
	},
	// 修改回显
	// setFormFields(submit, data) {
	// 	submit.forEach(v => {
	// 		for (let i in data) {
	// 			if (i === v.name) {
	// 				v.value = data[i]
	// 			}
	// 		}
	// 	})
	// 	return submit
	// },
	// 截取条码号为12位数
	getSpecCode(code){
		return code.substr(0, 12)
	},
	// 分隔条码号
	getSplitSpecCode(code){
		if(code){
			return code.length > 12 ?  code.substr(0, 12) + '-' + code.substr(-2, 2) : code
		}else{
			return '--'
		}
	},
	// 获取状态
	getState(data, text, name='name',value='value'){
		if(this.hasArray(data)){
			const rows = data.filter(v=> {
				if(isNaN(+text)){
					return v[value] === text
				}else{
					return +v[value] === +text
				}
			})
			return this.hasArray(rows) ? rows[0][name] : '--'
		}else{
			return '--'
		}
	},
	delay(fn){
		setTimeout(fn, 80)
	},
	// 获取地区提交数据
	getAddress(data){
		if(this.hasArray(data)){
			return {
				country_id: '100000',
				province_id: data[0], 
				city_id: data[1], 
				area_id: data[2]
			}
		}else{
			return data
		}
	},
	// 获取图片前缀
	getImagePrefix(url){
		if(url && this.isString(url)){
			if(url.indexOf('http') >= 0) {
				return url
			}else{
				const { img_domain } = this.getUser() || {}
				const prefix = img_domain ? img_domain : ''
				return url.indexOf(prefix) !== -1 ? url : prefix + url
			}
		}else{
			return null
		}
	},
	// 设备搜索
	// searchDevice({ rows }){
	// 	if(rows){
	// 		this.deviceParam = { device_id: rows.value, device_name: rows.device_name }
	// 	}else{
	// 		this.deviceParam = { device_id: '', device_name: '' }
	// 	}
	// } 
	// 重置模板
	resetTemplate(){
		this.setState({ hide: true}, ()=>{
			this.setState({ hide:false })
		})
	},
	// 获取设置搜索名
	searchDevice(option){
		const { rows } = option || {} 
		if(_.hasObject(rows)){
			this.model = {...this.model, device_name: rows.device_name }
		}else{
			delete this.model.device_name
			delete this.model.device_id
		}
	},
	// url 汉字编码与解码
	encode(str){return encodeURIComponent(str) },
	decode(str){return decodeURIComponent(str)},
	// 获取 selectedRows
	getSelectedRows(rows){
		if(rows){
			return window.$fn.hasArray(rows) ? rows[rows.length - 1] : null
		}else{
			if(this.state){
				const { selectedRows } = this.state
				if(window.$fn.hasArray(selectedRows)){
					return selectedRows[selectedRows.length - 1]
				}else{
					if(Array.isArray(selectedRows)){
						window.$fn.toast('selectedRows 为空')
					}else{
						window.$fn.toast('selectedRows 未先声明')
					}
					return {}
				}
			}
		}
	},
	// 表单数据加载字段错提示
	formTest(data, idStr, nameStr){
		if(window.$config.env){
			if(window.$fn.isArray(data)){
				if(window.$fn.hasArray(data)){
					const stack = data[0]
					const value = stack[idStr]
					const name = stack[nameStr]
					if(value === undefined && name === undefined){
						return `${idStr}、${nameStr} 不存在`
					}else if(name === undefined){
						return `${nameStr} 不存在`
					}else if(value === undefined){
						return `${idStr} 不存在`
					}else{
						return null
					}
				}else{
					return '数据为空'
				}
			}else{
				return '数据不存在，请检查'
			}
		}else{
			return null
		}
	},
	// 数组对象去重
	onlyObject(arr,key){
		let result = []
		let obj = {}
		arr.forEach(function(v){
			if(!obj[v[key]]){
				result.push(v)
				obj[v[key]] = true
			}
		})
		return result
	},
	// 复制
	copyText(value){
		let el = document.querySelector('#copyText')
		if(!el){
			el = document.createElement('textarea')
			el.id = 'copyText'
			el.style.cssText = 'position:absolute;left:0;bottom:-10000px;z-index:-1;opacity:0'
			el.readOnly = 'readOnly'
			document.body.appendChild(el)
		}
		el.value = value
		el.select()
		document.execCommand('copy')
		window.$fn.msg.success('复制成功', 200)
	},
	//  判断是否图片格式 2022年11月7日17:49:38 敖得卓
	isAssetTypeAnImage: (val) =>  {
		if(!val) return false
		const index= val.lastIndexOf(".");
		const ext = val.substr(index+1);
		return ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff'].indexOf(ext.toLowerCase()) !== -1
	}
}

export default _